import { Vec2 } from "cc"
import { Vec3 } from "cc"
import { UITransform } from "cc"
import { EventTouch } from "cc"
import { _decorator, Component, Node } from "cc"
import { util } from "../util/util"
import { Player } from "./Player"
const { ccclass, property } = _decorator

@ccclass("TouchLayerManager")
export class TouchLayerManager extends Component {

  private arrNodeTouch:Node[] = []

  private arrRolePlayer:Player[] = []
  start() {
    for(let key in this.node.children){
      this.arrNodeTouch.push(this.node.children[key])
    }
  }

  protected onEnable(): void {
    this.node.on(Node.EventType.TOUCH_START, this._touchStartEvent, this)
    this.node.on(Node.EventType.TOUCH_MOVE, this._touchMoveEvent, this)
    this.node.on(Node.EventType.TOUCH_END, this._touchEndEvent, this)
    this.node.on(Node.EventType.TOUCH_CANCEL, this._touchEndEvent, this)
  }

  protected onDisable(): void {
    this.node.off(Node.EventType.TOUCH_START, this._touchStartEvent, this)
    this.node.off(Node.EventType.TOUCH_MOVE, this._touchMoveEvent, this)
    this.node.off(Node.EventType.TOUCH_END, this._touchEndEvent, this)
    this.node.off(Node.EventType.TOUCH_CANCEL, this._touchEndEvent, this)
  }


  convertToNodeSpaceAR(touchPos: Vec2) {
    let uiTransform = this.node.getComponent(UITransform)
    return uiTransform.convertToNodeSpaceAR(new Vec3(touchPos.x, touchPos.y))
  }

  private _isTouch: boolean = false
  private _isCanTouch: boolean = true

  private curTouchIndex:number = -1

  private _touchStartEvent(event: EventTouch) {
    if (!this._isCanTouch) return
    this._isTouch = true
    let touchPos = this.convertToNodeSpaceAR(event.getUILocation())
    for(let i:number = 0;i < this.arrNodeTouch.length;i++){
      const node = this.arrNodeTouch[i]
      const dis  = util.getTwoPosXYLength(touchPos.x,touchPos.y,node.position.x,node.position.y)
      if(dis < 50){
        this.curTouchIndex = i
        break
      }
    }
    console.log("curTouchIndex:",this.curTouchIndex)
  }
  private _touchMoveEvent(event: EventTouch) {
    if (!this._isTouch ||!this._isCanTouch) return
    let touchPos = this.convertToNodeSpaceAR(event.getUILocation())

  }
  private _touchEndEvent(event: EventTouch) {
    if (!this._isTouch ||!this._isCanTouch) return
    this._isTouch = false
    let touchPos = this.convertToNodeSpaceAR(event.getUILocation())
    this.curTouchIndex = -1
  }

  update(deltaTime: number) {}
}
